/**
 * @file HTTP请求类
 * @author WuFeng
 * @copyright 百旺祥云
 * @createDate 2020-03-09 15:34:00
 */

import axios from 'axios'
import { Message /*, MessageBox*/ } from 'element-ui'
import store from '../store'
import { TOKEN_KEY } from '@/config'
import { getToken } from './auth'

// 创建axios实例
const service = axios.create({
  baseURL: process.client ? process.env.BASE_API : process.env.BASE_API_LAN, // api的base_url
  withCredentials: true,
  timeout: 50000 // 请求超时时间
})

// request拦截器
service.interceptors.request.use(config => {
  config.headers.post['Content-Type'] = 'application/json;charset=UTF-8'
  if (process.client) {
    if (getToken(null)) {
      config.headers[TOKEN_KEY] = getToken(null) // token，标识用户登陆状态
    }
  } else {
    if (store().getters['user/token']) {
      config.headers[TOKEN_KEY] = store().getters['user/token'] // token，标识用户登陆状态
    }
  }
  return config
}, error => {
  // 处理请求错误
  console.log(error) // for debug
  Promise.reject(error)
})

// respone拦截器
service.interceptors.response.use(
  response => {
    /**
    * code：SUCCESS,FAIL,EXCEPTION,UNLOGIN,ILLEGAL
    */
    const res = response.data
    // 成功状态
    if (res.code === 200) {
      res.mesg = res.mesg || res.mesg || ''
      return Promise.resolve(response.data)
    } /*除成功状态之外的状态一并拦截*/ else {
      res.mesg = res.mesg || res.mesg || '服务器出了些小问题，请稍后再试！'
      if (response.config.headers['Error-Echo']) {
        Message({
          message: res.message,
          type: 'error',
          duration: 5 * 1000
        })
      }
      console.log('request error ---------------- ')
      console.log(response.data)
      return Promise.reject(response.data)
    }
  },
  error => {
    console.log('request error ---------------- ')
    console.log(error)
    return Promise.reject(error)
  }
)

export default service
